import {ComponentFactoryResolver, ComponentRef, Injectable, Type, ViewContainerRef} from '@angular/core';
import {BaseComponent} from '../entity/base-component';

@Injectable({
    providedIn: 'root'
})
export class MapPluginsService {

    compRefs: ComponentRef<any>[] = []; //  加载的组件实例
    private viewContainerRef: ViewContainerRef;

    constructor(private resolver: ComponentFactoryResolver) {
    }

    /**
     * 设置mapPlugins 容器
     * @param viewContainerRef mapPlugins 容器
     */
    setMapContainer(viewContainerRef: ViewContainerRef) {
        if (this.viewContainerRef && !viewContainerRef) {
            for (const f of this.compRefs) {
                f.destroy();
            }
        }
        this.viewContainerRef = viewContainerRef;
    }

    loadComponent<T>(component: Type<T>): ComponentRef<T> {
        if (component == null) {
            return null;
        }
        const factory = this.resolver.resolveComponentFactory(component);
        const compRef: ComponentRef<T> = this.viewContainerRef.createComponent(factory);
        const base: BaseComponent = compRef.instance as unknown as BaseComponent;
        if (base.closeEvent) {
            base.closeEvent.subscribe(() => {
                console.log(`exec ${compRef} close`);
                compRef.destroy();
            });
        }
        compRef.onDestroy(() => {
            console.log(`${compRef} closed!`);
        });

        this.compRefs.push(compRef);

        return compRef;
    }
}
